﻿
@{
    ViewBag.Title = "UploadDocument";
}

<h2>UploadDocument</h2>

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" id="imgInp" name="file" />
    <table>
        <tbody>
        </tbody>
    </table>

    <input type="submit" name="Submit" id="Submit" value="Upload" />
}


<h1>ajax upload image</h1>
<input type="file" name="etlfileToUpload" id="etlfileToUpload" />

<input type="button" id="btn-ajax-upload" value="ajax-upload" />
<span id="uploading"></span>
@section Scripts{

    <script>
        $("#btn-ajax-upload").click(function () {
            UploadFile();
        });
    </script>

    <script>
        // Call this function on upload button click after user has selected the file 
        function UploadFile() {
            var file = document.getElementById('etlfileToUpload').files[0];
            var fileName = file.name;
            var fd = new FormData();
            fd.append("fileData", file);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
            xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
            xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
            xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
            xhr.open("POST", "@Url.Action("Upload","Home")", true);
            xhr.send(fd);
        }


        function UploadProgress(evt) {
            if (evt.lengthComputable) {

                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                while (percentComplete < 100)
                {
                    UploadProgress(evt);
                }
                $("#uploading").text(percentComplete + "% ");
            }
        }

        function UploadComplete(evt) {
            if (evt.target.status == 200)
                //alert(evt.target.responseText);
                console.log("complete");
            else {
                alert("Error Uploading File");
            }
        }

        function UploadFailed(evt) {
            alert("There was an error attempting to upload the file.");
        }

    </script>



    <script>
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $("tbody").append("<tr>" + "<td>" + "<img src='" + e.target.result + "' />" + "</td>" + "</tr>");

                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        $("#imgInp").change(function () {
            readURL(this);
        });
    </script>
}